package com.tsy.server.system.service;

import com.tsy.server.component.redis.RedisKeyConstant;
import com.tsy.server.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

/**
 * 邮件服务
 */
@Slf4j
@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${verification.code.expiration}")
    private Integer codeExpiration;

    /**
     * 发送验证码
     *
     * @param to 收件人
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String to) {
        // 生成6位随机验证码
        String code = generateVerificationCode();
        // 构建邮件内容
        String subject = "无人机管理平台 - 邮箱验证码";
        String content = "<div style=\"font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;\">"
                + "<h2 style=\"color: #333;\">无人机管理平台 - 邮箱验证</h2>"
                + "<p style=\"color: #555; font-size: 16px;\">您好，感谢您使用无人机管理平台！</p>"
                + "<p style=\"color: #555; font-size: 16px;\">您的验证码是：</p>"
                + "<div style=\"background-color: #f5f5f5; padding: 10px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; color: #333; margin: 15px 0;\">"
                + code
                + "</div>"
                + "<p style=\"color: #555; font-size: 14px;\">验证码有效期为" + codeExpiration + "分钟，请勿将验证码泄露给他人。</p>"
                + "<p style=\"color: #888; font-size: 12px; margin-top: 30px;\">此邮件由系统自动发送，请勿回复。</p>"
                + "</div>";

        try {
            // 发送邮件
            sendHtmlMail(to, subject, content);
            // 将验证码保存到Redis，设置过期时间
            String key = RedisKeyConstant.buildVerifyCodeKey(to);
            redisUtil.set(key, code, codeExpiration * 60L);
            return true;
        } catch (Exception e) {
            log.error("发送验证码邮件失败：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 验证验证码
     *
     * @param email 邮箱
     * @param code  验证码
     * @return 是否验证成功
     */
    public boolean verifyCode(String email, String code) {
        String key = RedisKeyConstant.buildVerifyCodeKey(email);
        Object savedCode = redisUtil.get(key);
        if (savedCode == null) {
            return false;
        }
        boolean result = code.equals(savedCode.toString());
        if (result) {
            // 验证成功后删除验证码
            redisUtil.delete(key);
        }
        return result;
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     * @throws MessagingException 邮件发送异常
     */
    private void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        mailSender.send(message);
        log.info("HTML邮件已发送至：{}", to);
    }

    /**
     * 生成6位随机验证码
     *
     * @return 验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}